using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
using System.Xml;
using System.Windows.Forms;

namespace TTBox
{
public class ATCMDData
{
    // Fields
    private string cmdSent;
    public bool dataReceived;
    public string ImeiNo = "";
    public bool ModemConnected;
    private byte[] rBuf;
    private int rBufLen;
    public string resText;
    public bool retVal;
    public bool sendCmd;
    private SerialPort sp;
    private string temp;

    // Methods
    private int chkRes(byte[] response, int responseLen)
    {
        short num = 2;
        try
        {
            if ((response[--responseLen] != 10) || (response[--responseLen] != 13))
            {
                return num;
            }
            if (response[--responseLen] == 0x4b)
            {
                if (response[--responseLen] == 0x4f)
                {
                    num = 1;
                }
                return num;
            }
            if ((((response[responseLen] == 0x52) && (response[--responseLen] == 0x4f)) && ((response[--responseLen] == 0x52) && (response[--responseLen] == 0x52))) && (response[--responseLen] == 0x45))
            {
                num = 0;
            }
        }
        catch (Exception exception)
        {
            throw exception;
        }
        return num;
    }

    public void ClosePort()
    {
        if ((this.sp != null) && this.sp.IsOpen)
        {
            this.sp.Close();
        }
    }

    private bool ConnectModem()
    {
        int num = 10;
        int num2 = 0;
        DateTime now = DateTime.Now;
        try
        {
            if (this.ConnectPort())
            {
                while ((num > 0) && (num2 <= 2))
                {
                    if (this.sendCmd)
                    {
                        num--;
                        now = DateTime.Now;
                    }
                    if (!this.sendCmd)
                    {
                        TimeSpan span = (TimeSpan) (DateTime.Now - now);
                        if (span.Seconds > 9)
                        {
                            break;
                        }
                    }
                    if (this.retVal)
                    {
                        num2++;
                    }
                    switch (num2)
                    {
                        case 0:
                            if (this.sendCmd)
                            {
                                this.InitialiseATCommand();
                            }
                            break;

                        case 1:
                            if (this.sendCmd)
                            {
                                this.SetEchoOnOff(false);
                            }
                            break;

                        case 2:
                            if (this.sendCmd)
                            {
                                this.SendCmdPINNo("?");
                            }
                            break;
                    }
                }
                if (num2 > 2)
                {
                    this.retVal = true;
                }
                else
                {
                    this.retVal = false;
                }
            }
        }
        catch (Exception exception)
        {
            MessageBox.Show(exception.Message, "Connect Modem");
            this.retVal = false;
        }
        return this.retVal;
    }

    private bool ConnectPort()
    {
        bool flag = false;
        this.sp.PortName = "COM2";
        this.sp.BaudRate = 0x1c200;
        this.sp.DataBits = 8;
        this.sp.Parity = Parity.None;
        this.sp.StopBits = StopBits.One;
        try
        {
            if (!this.sp.IsOpen)
            {
                this.sp.Open();
                this.sp.WriteTimeout = 0x3e8;
                this.sp.ReadTimeout = 0x3e8;
                this.sp.ReceivedBytesThreshold = 1;
                return true;
            }
            flag = true;
        }
        catch (Exception exception)
        {
            throw exception;
        }
        return flag;
    }

    public void Create_Identification_Frame(ref byte[] byteFrame)
    {
        string s = "";
        try
        {
            s = "A0A100" + GPSData.idnFrameId + GPSData.PNDSimNo + GPSData.imeiNO + GPSData.imsiNO + "B2B3";
            string str2 = Convert.ToString(s.Substring(8, s.Length - 12).Length, 0x10);
            if (str2.Length == 1)
            {
                str2 = "0" + str2;
            }
            s = s.Remove(4, 2).Insert(4, str2);
            byteFrame = new byte[s.Length];
            byteFrame = Encoding.ASCII.GetBytes(s);
        }
        catch (Exception exception)
        {
            byteFrame = null;
            throw exception;
        }
    }

    private string getCommand(ATCommands cmdType, string val)
    {
        switch (cmdType)
        {
            case ATCommands.initialiseATCommand:
                return "AT\r\n";

            case ATCommands.setEchoOnOff:
                return ("ATE" + val + "\r\n");

            case ATCommands.getIMEINo:
                return "AT+CGSN\r\n";

            case ATCommands.getIMSINo:
                return "AT+CIMI\r\n";

            case ATCommands.getPINNo:
                return ("AT+CPIN=" + val + "\r\n");
        }
        return "";
    }

    public string GetIMEINo()
    {
        if (this.ModemConnected)
        {
            int num = 3;
            while (num > 0)
            {
                if (!this.sendCmd || !this.SendCmdIMEINo())
                {
                    continue;
                }
                DateTime now = DateTime.Now;
                while (!this.dataReceived)
                {
                    TimeSpan span = (TimeSpan) (DateTime.Now - now);
                    if (span.Seconds > 10)
                    {
                        break;
                    }
                }
                if (!this.dataReceived)
                {
                    this.sendCmd = true;
                    num--;
                }
                if (this.retVal)
                {
                    return this.resText.Trim();
                }
                num--;
            }
        }
        return "";
    }

    public string getKeyValue(string key)
    {
        string message = "";
        try
        {
            XmlTextReader reader = new XmlTextReader(GPSData.filePath);
            bool flag = false;
            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element:
                        if ((!reader.HasAttributes || !(reader.GetAttribute("key") == key)) || (reader.GetAttribute("value") == null))
                        {
                            break;
                        }
                        return reader.GetAttribute("value");

                    case XmlNodeType.Attribute:
                    {
                        continue;
                    }
                    case XmlNodeType.Text:
                        if (!flag)
                        {
                            continue;
                        }
                        return reader.Value;

                    default:
                    {
                        continue;
                    }
                }
                if (reader.HasAttributes && (reader.GetAttribute("name") == key))
                {
                    flag = true;
                }
            }
            message = "null";
        }
        catch (XmlException exception)
        {
            message = exception.Message;
            throw exception;
        }
        catch (Exception exception2)
        {
            message = exception2.Message;
            throw exception2;
        }
        return message;
    }

    private bool InitialiseATCommand()
    {
        return this.sendATCommand(this.getCommand(ATCommands.initialiseATCommand, ""));
    }

    private void reInitVar(string cmd)
    {
        this.resText = "";
        this.rBufLen = 0;
        this.cmdSent = cmd;
        this.retVal = false;
        this.sendCmd = false;
        this.dataReceived = false;
    }

    private bool sendATCommand(string cmd)
    {
        try
        {
            this.temp = this.sp.ReadExisting();
            this.reInitVar(cmd);
            this.sp.Write(cmd);
            return true;
        }
        catch
        {
            return false;
        }
    }

    public bool SendCmdIMEINo()
    {
        return this.sendATCommand(this.getCommand(ATCommands.getIMEINo, ""));
    }

    private bool SendCmdIMSINo()
    {
        return this.sendATCommand(this.getCommand(ATCommands.getIMSINo, ""));
    }

    public bool SendCmdPINNo(string PinCode)
    {
        return this.sendATCommand(this.getCommand(ATCommands.getPINNo, PinCode));
    }

    private bool SetEchoOnOff(bool Value)
    {
        return this.sendATCommand(this.getCommand(ATCommands.setEchoOnOff, Value ? "1" : "0"));
    }

    private void Sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            MessageBox.Show("Sp_DataReceived");
            Application.DoEvents();
            if (this.sp.BytesToRead > 0)
            {
                MessageBox.Show(this.sp.BytesToRead.ToString(), "Sp_DataReceived");
                Application.DoEvents();
                this.resText = this.sp.ReadExisting().Trim();
                if (this.resText != "")
                {
                    MessageBox.Show(this.resText, "Received Response for Command : " + this.cmdSent);
                    Application.DoEvents();
                    if (this.resText.IndexOf("OK") >= 0)
                    {
                        this.dataReceived = this.sendCmd = this.retVal = true;
                    }
                    else if (this.resText.IndexOf("ERROR") >= 0)
                    {
                        this.dataReceived = this.sendCmd = this.retVal = false;
                    }
                    else
                    {
                        this.dataReceived = this.sendCmd = this.retVal = false;
                    }
                }
            }
        }
        catch
        {
            this.retVal = this.dataReceived = this.sendCmd = false;
        }
        finally
        {
            if (this.dataReceived)
            {
                this.cmdSent = "";
            }
        }
    }

    // Nested Types
    private enum ATCommands
    {
        initialiseATCommand,
        setEchoOnOff,
        getIMEINo,
        getIMSINo,
        getPINNo
    }

    private enum ATSuffixes : byte
    {
        ANSWER_SUFFIX = 0x3d,
        COMMAND_PREFIX = 0x2b,
        READ_SUFFIX = 0x3a,
        REPLY_SUFFIX = 0x3f
    }

    private enum ReturnType : byte
    {
        AT_ANSWER = 4,
        AT_ERROR = 1,
        AT_ERROR_CME = 3,
        AT_ERROR_CMS = 2,
        AT_NULL = 7,
        AT_OK = 0,
        AT_OTHER = 5,
        AT_TIMEOUT = 6
    }
}

 
 

}
